package com.neusoft.databus.agent.pool.netty;

import java.util.List;

import org.apache.commons.pool2.PooledObject;
import org.springframework.stereotype.Component;

import com.neusoft.databus.common.connection.SocketConnection;
import com.neusoft.databus.common.pool.AbstractPoolFactory;
import com.neusoft.databus.common.utils.DigitalUtils;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class NettyFactory extends AbstractPoolFactory<SocketConnection, NettyWrapper> {

    @Override
    public NettyWrapper create(SocketConnection key) throws Exception {

        final NettyWrapper client = new NettyWrapper();

        final NioEventLoopGroup g = new NioEventLoopGroup();
        final Bootstrap b = new Bootstrap();
        b.group(g).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                final ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("loggingHandler", new LoggingHandler(LogLevel.DEBUG));
                pipeline.addLast(new ByteToMessageDecoder() {

                    @Override
                    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
                        int totalLength = in.readableBytes();
                        NettyFactory.log.info("接收包长度：{}", totalLength);

                        while (in.readableBytes() >= 8) {
                            final int packetLen = in.getShort(in.readerIndex() + 4) + 6;
                            NettyFactory.log.info("待拆分包长度：{}", packetLen);
                            totalLength = in.readableBytes();
                            if (totalLength < packetLen) {
                                NettyFactory.log.info("分包长度不足，不读取");
                                break;
                            }
                            this.decode(in, out);
                        }
                    }

                    private void decode(ByteBuf in, List<Object> out) {
                        try {
                            final int totalLength = in.readableBytes();
                            final int packetLen = in.getShort(in.readerIndex() + 4) + 6;
                            if (totalLength >= packetLen) {
                                final byte[] packet = new byte[packetLen];
                                in.readBytes(packet);
                                NettyFactory.log.info("拆包：{}", DigitalUtils.bytesToHexString(packet));
                                out.add(packet);
                            }
                            NettyFactory.log.info("剩余包长度：{}", in.readableBytes());
                        } catch (final Exception e) {
                            NettyFactory.log.error(e.getMessage(), e);
                        }
                    }
                });
                pipeline.addLast("processHandler", client);
            }
        }).option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.AUTO_READ, true);

        final ChannelFuture f = b.connect(key.getIpAddress(), key.getPort()).await();
        f.addListener(future -> {
            if (future.isSuccess()) {
                client.setChannel(f.channel());
            } else {
                NettyFactory.log.error("failed to connect {}:{}", key.getIpAddress(), key.getPort());
            }
        });
        return client;
    }

    @Override
    public boolean validateObject(SocketConnection key, PooledObject<NettyWrapper> p) {
        if ((null == p.getObject().getChannel()) || !p.getObject().getChannel().isActive()) {
            return false;
        }
        return true;
    }

    @Override
    public void destroy(NettyWrapper v) {
        if (null != v.getChannel()) {
            v.getChannel().close();
        }

    }

    @Override
    public void passivateObject(SocketConnection key, PooledObject<NettyWrapper> p) throws Exception {
        p.getObject().clear();
    }

}
